<template>
    <div class="sell_records">
      <van-nav-bar
        title="卖出记录"
        left-arrow
        @click-left="$router.back()"
        left-text="返回"
      />
      <van-notice-bar mode="closeable" left-icon="volume-o">
        撤单后，股份就会自动回到我的股份中，望周知！
      </van-notice-bar>
      <van-cell-group>
        <van-cell center title="已挂牌股份数量" :value="myAllStockInfo.sell ? myAllStockInfo.sell + '股' : '暂无'" size="large" />
        <van-cell center title="剩余股份数量" :value="myAllStockInfo.depo ? myAllStockInfo.depo + '股' : '暂无'" size="large" />
        <div style="margin: 16px;">
          <van-button round block color="#1989FA" native-type="button" @click="continueSell(myAllStockInfo)">
            继续卖出
          </van-button>
        </div>
      </van-cell-group>

      <van-dropdown-menu>
        <van-dropdown-item v-model="value1" :options="option1" disabled />
        <van-dropdown-item v-model="value2" :options="option2"  @change="toGetNeedList"/>
      </van-dropdown-menu>

      <van-cell>
        <van-row style="text-align: center; vertical-align: center" align="center" type="flex" justify="space-between">
          <van-col span="7">时间</van-col>
          <van-col span="4">每股股价(￥)</van-col>
          <van-col span="4">卖出数量</van-col>
          <van-col span="4">可卖出到账</van-col>
          <van-col span="4">{{value2 === 'cancelled' ? '说明' : '操作'}}</van-col>
        </van-row>
      </van-cell>


      <div v-if="sellRecordsList.length">
        <van-cell  v-for="item in sellRecordsList" :key="item.id" style="font-size: 12px">
          <van-row type="flex" style="text-align:center" align="center" justify="space-between">
            <van-col span="7">{{item.createdate}}</van-col>
            <van-col span="4">{{(item.price / 1000).toFixed(3)}}</van-col>
            <van-col span="4">{{item.amount}}</van-col>
            <van-col span="4">{{(item.price * item.amount / 1000).toFixed(3)}}</van-col>
            <van-col span="4" v-show="value2 === 'cancelled'">已撤单</van-col>
            <van-col span="4" v-show="value2 === 'completeDeal'">交易完成</van-col>
            <van-col span="4" v-show="value2 === 'unSell'">
              <van-button color='#EE0A24' size="small" @click="toCancelStock(item.id)">撤单</van-button>
            </van-col>
          </van-row>
        </van-cell>
        <van-pagination
          v-model="pageIndex"
          style="margin-top: 3px"
          :total-items="totalRecord"
          :items-per-page="pageSize"
          force-ellipses
          @change="handleChange"
        />
      </div>

      <van-divider style="margin-top: 60px" v-else>暂无记录</van-divider>
    </div>
</template>

<script>
  import { Dialog, Toast } from 'vant';

  export default {
    name: 'sellRecords',
    data(){
      return {
        value1: 0,
        value2: 'unSell',
        option1: [
          { text: '股份的卖出状态', value: 0 },
        ],
        option2: [
          { text: '挂单（正在卖出）', value: 'unSell' },
          { text: '已撤单', value: 'cancelled' },
          { text: '已成交', value: 'completeDeal' },
        ],
        myAllStockInfo: {},
        sellRecordsList:[],
        stockId: '',
        needPrice: '',
        pageIndex: 1,
        pageSize: 20,
        totalRecord: 0,
      }
    },
    created() {
      const stockId = JSON.parse(localStorage.getItem('stockItem')).id
      if (stockId){
        this.stockId = stockId
      };

      // 开盘价
      const price = this.$route.params.price || localStorage.getItem('needPrice')
      // 若有obj, 则保存
      if (price) {
        if (this.$route.params.price) {
          localStorage.setItem('needPrice', price)
        }
        this.needPrice = JSON.parse(localStorage.getItem('needPrice'))
      } else {
        this.$router.push('/groupStock/stockMarket')
        localStorage.removeItem('needPrice')
      }


    },
    mounted() {
      if (this.stockId){
        // 初始化
        const params_0 = {
          id: this.stockId,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        }
        // 正在挂单的记录
        this._getUnSellList(params_0)
      }
    },
    methods: {
      toGetNeedList(value){
        this.pageIndex = 1

        // 固定参数
        const params_all = {
          id: this.stockId,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        };


        if (value === 'unSell'){
          // 挂单
          this._getUnSellList(params_all)
        } else if (value === 'completeDeal'){
          // 已成交
          this._getSellRecordList(params_all)
        } else if (value === 'cancelled'){
          // 撤销记录
          this._getMyRevokeList(params_all)
        }
      },

      /*
      * 封装函数
      */

      // 挂单列表
      _getUnSellList(params){
        // 挂单列表
        this.$api.stock.reqMySellingList(params).then(res =>{
          if(res.code===200){
            this.sellRecordsList = res.data.items
            this.totalRecord = res.data.total
          }
        });
        // 当前的持有股票
        this._getMyHoldStock()
      },

      // 成交列表
      _getSellRecordList(params){
        this.$api.stock.reqSellRecordList(params).then(res =>{
          if(res.code===200){
            this.sellRecordsList = res.data.items
            this.totalRecord = res.data.count
            // 当前的持有股票
            this._getMyHoldStock()
          }
        })
      },

      // 撤销列表
      _getMyRevokeList(params){
        this.$api.stock.reqMyRevokeList(params).then(res =>{
          if(res.code===200){
            this.sellRecordsList = res.data.items
            this.totalRecord = res.data.total || res.data.count || 0
            // 当前的持有股票
            this._getMyHoldStock()
          }
        })
      },

      // 当前持有股份
      _getMyHoldStock(){
        this.$api.stock.reqMyHoldStock(this.stockId).then(res =>{
          if(res.code===200){
            this.myAllStockInfo = res.data
          }
        })
      },

      toCancelStock(id){
        Dialog.confirm({
          title: '股份撤单',
          message: '你确定撤单吗？撤单后，股份会撤回到我的股份中！',
        })
          .then(() => {
            // 点击撤单
            this.$api.stock.reqRevokeSell(id).then(res =>{
              if(res.code===200){
                Toast.success(res.data);
                // 重新获取
                const params_1 = {
                  id: this.stockId,
                  pageIndex: this.pageIndex,
                  pageSize: this.pageSize,
                }
                this._getUnSellList(params_1)
              }
            })
          })
          .catch(() => {
            // on cancel
          });
      },

      // 继续卖出
      continueSell(stockInfo){
        if( (stockInfo.depo)  && (stockInfo.depo)*1 > 0){
          const obj = {
            stockid: this.stockId,
            amount: stockInfo.depo,
            ysdayprice: this.needPrice
          };

          this.$router.push({
            name: 'sellStock',
            params: {
              myStockInfo: JSON.stringify(obj)
            }
          })
        } else {
          Toast('尚未持股，无法卖出。请先买入股份！');
        }
      },


      handleChange(value){
        const params = {
          id: this.stockId,
          pageIndex: value,
          pageSize: this.pageSize,
        };

        if (this.value2 === 'unSell'){
          // 挂单分页
          this._getUnSellList(params)
        } else if (this.value2 === 'completeDeal'){
          // 成交分页
          this._getSellRecordList(params)
        } else if(this.value2 === 'cancelled'){
          // 撤单分页
          this._getMyRevokeList(params)
        }

      }
    },
  }
</script>

<style scoped>

</style>
